package com.jic.order.controller.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.order.entity.OrderInvoice;
import com.jic.order.request.*;
import com.jic.order.response.FrontAllOrderInfo;
import com.jic.order.response.FrontOrderDetailInfo;
import com.jic.order.response.FrontOrderGoodsInfo;
import com.jic.order.response.UnifiedOrderResponses;
import com.jic.order.rest.request.OrderBaleRestRequest;
import com.jic.order.rest.request.OrderInvoiceRequest;
import com.jic.order.rest.request.OrderSensitiveRequest;
import com.jic.order.rest.response.OrderBaleInfoResponse;
import com.jic.order.rest.response.OrderSensitiveResponse;
import com.jic.order.rest.response.ProductCommentRestResponse;
import com.jic.order.service.*;
import com.jic.product.store.MStoreApi;
import com.jic.product.store.request.ProductCommentRequest;
import com.jic.product.store.response.ProductCommentResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "API-订单")
@RequestMapping(value = "order")
@RestController
public class OrderRest {

	@Autowired
	RedisClientTemplate redisClientTemplate;
	@Autowired
	private OrderQueryService orderQueryService;
	@Autowired
	private OrderOperateService orderOperateService;
	@Autowired
	private OrderInvoiceService orderInvoiceService;
	@Autowired
	private OrderBaleService orderBaleService;
	@Autowired
	private MStoreApi mStoreApi;
	@Autowired
	private WXService wxService;
	@Autowired
	private OrderLogisticsService orderLogisticsService;

	@ApiOperation(value = "创建秒杀订单")
	@RequestMapping(value = "createSpikeOrder", method = RequestMethod.POST)
	public RestResult<String> createSpikeOrder(@RequestBody CreateSpikeOrderRequest request) {
		return orderOperateService.createSpikeOrder(request);
	}

	@ApiOperation(value = "创建拼团订单")
	@RequestMapping(value = "createJoinGroupOrder", method = RequestMethod.POST)
	public RestResult<String> createJoinGroupOrder(@RequestBody CreateJoinGroupOrderRequest request) {
		return orderOperateService.createJoinGroupOrder(request);
	}

	@ApiOperation(value = "查询订单列表")
	@RequestMapping(value = "queryAllList", method = RequestMethod.POST)
	public RestResult<List<FrontAllOrderInfo>> queryAllList(@RequestBody UserPageQuery request) {
		return orderQueryService.queryAllList(request);
	}

	@ApiOperation(value = "查询订单详情")
	@RequestMapping(value = "queryDetail", method = RequestMethod.POST)
	public RestResult<FrontAllOrderInfo> queryDetail(@RequestBody CommonOrderNoRequest request) {
		return orderQueryService.queryDetail(request);
	}

	@ApiOperation(value = "付款")
	@RequestMapping(value = "pay", method = RequestMethod.POST)
	public RestResult<String> pay(@RequestBody FrontPayOrderRequest request) {
		log.info("付款，request={}", JSON.toJSONString(request));
		return orderOperateService.pay(request);
	}

	@ApiOperation(value = "取消订单")
	@RequestMapping(value = "close", method = RequestMethod.POST)
	public RestResult<String> close(@RequestBody FrontCloseOrderRequest request) {
		log.info("取消订单，request={}", JSON.toJSONString(request));
		return orderOperateService.close(request);
	}

	@ApiOperation(value = "确认收货")
	@RequestMapping(value = "confirmShip", method = RequestMethod.POST)
	public RestResult<String> confirmShip(@RequestBody FrontConfirmShipOrderRequest request) {
		log.info("确认收货，request={}", JSON.toJSONString(request));
		return orderOperateService.confirmShip(request);
	}

	@ApiOperation(value = "保存订单发票信息")
	@RequestMapping(value = "saveOrderInvoice", method = RequestMethod.POST)
	public RestResult<Long> saveOrderInvoice(@RequestBody OrderInvoiceRequest orderInvoiceRequest) {
		/*if (StringUtils.isEmpty(orderInvoiceRequest.getOrderNo())) {
			return RestResult.error("9999", "订单号不能为空");
		}*/
		OrderInvoice orderInvoice = new OrderInvoice();
		orderInvoice.setOrderNo(orderInvoiceRequest.getOrderNo());
		/*List<OrderInvoice> orderInvoiceList = orderInvoiceService.query(orderInvoice);
		if (orderInvoiceList.size() > 0) {
			return RestResult.error("9999", "订单号已申请发票请勿重新申请");
		}*/
		BeanUtils.copyProperties(orderInvoiceRequest, orderInvoice);
		return RestResult.success(orderInvoiceService.insert(orderInvoice));
	}

	@ApiOperation(value = "查看物流信息")
	@RequestMapping(value = "getDeliveryByOrderNo", method = RequestMethod.POST)
	public RestResult<OrderBaleInfoResponse> getDeliveryByOrderNo(@RequestBody OrderBaleRestRequest orderBaleRequest) {
		return RestResult.success(orderBaleService.getDeliveryByOrderNo(orderBaleRequest));
	}

	@ApiOperation(value = "查询我的订单评价")
	@RequestMapping(value = "getOrderSensitiveList", method = RequestMethod.POST)
	public RestResult<List<OrderSensitiveResponse>> getOrderSensitiveList(@RequestBody OrderSensitiveRequest orderSensitiveRequest) {
		// 获取用户id
		String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + orderSensitiveRequest.getToken());
		if (StringUtils.isEmpty(userStr)) {
			return RestResult.error("4000", "非法请求");
		}
		Map<String, Object> userMap = JSONArray.parseObject(userStr, HashMap.class);
		String userId = userMap.get("id").toString();
		orderSensitiveRequest.setUserId(Long.parseLong(userId));
		List<FrontAllOrderInfo> frontAllOrderInfoList = orderQueryService.getOrderSensitiveList(orderSensitiveRequest);

		// 返回数据
		List<OrderSensitiveResponse> orderBaleDeliveryResponseList = new ArrayList<>();

		for (FrontAllOrderInfo frontAllOrderInfo : frontAllOrderInfoList) {
			for (FrontOrderDetailInfo temp : frontAllOrderInfo.getOrderList()) {
				OrderSensitiveResponse orderSensitiveResponse = new OrderSensitiveResponse();
				BeanUtils.copyProperties(temp, orderSensitiveResponse);
				if (temp.getOrderStatus() == 10) {
					for (FrontOrderGoodsInfo frontOrderGoodsInfo : orderSensitiveResponse.getGoodsInfoList()) {
						ProductCommentRequest productCommentRequest = new ProductCommentRequest();
						productCommentRequest.setProductId(frontOrderGoodsInfo.getGoodsId());
						productCommentRequest.setOrderNo(orderSensitiveResponse.getOrderNo());
						RestResult<ProductCommentResponse> restResult = mStoreApi.getProductCommentByOrderNo(productCommentRequest);
						ProductCommentRestResponse productComment = new ProductCommentRestResponse();
						BeanUtils.copyProperties(restResult.getData(), productComment);
						frontOrderGoodsInfo.setProductComment(productComment);
					}
				}
				orderBaleDeliveryResponseList.add(orderSensitiveResponse);
			}
		}

		return RestResult.success(orderBaleDeliveryResponseList);
	}
	@PostMapping("/wxPay")
	public RestResult<Map> wxPay(@RequestBody FrontPayOrderRequest request) throws Throwable {
		return RestResult.success(wxService.unifiedOrder(request));
	}


	/**
	 * 支付异步结果通知，我们在请求预支付订单时传入的地址
	 */
	@PostMapping(value = "/notify")
	public String wxPayNotify(HttpServletRequest request) {
		System.out.println("======================微信支付异步结果通知开始=================================");
		String resXml = "";
		try {
			InputStream inputStream = request.getInputStream();
			//将InputStream转换成xmlString
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			StringBuilder sb = new StringBuilder();
			String line = null;
			try {
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
			} catch (IOException e) {
				log.error("notify异常:{}", e);
			} finally {
				try {
					inputStream.close();
				} catch (IOException e) {
					log.error("notify异常:{}", e);
				}
			}
			resXml = sb.toString();
			String result = wxService.payBack(resXml);
			return result;
		} catch (Exception e) {
			System.out.println("微信手机支付失败:" + e.getMessage());
			String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
			return result;
		}
	}

	/**
	 * 客服
	 * @param apiOrder
	 * @return
	 */
	@ApiOperation(value = "客服查询订单信息")
	@RequestMapping(value = "queryOrderInfoOrList", method = RequestMethod.POST)
	public Map queryOrderInfoOrList(@RequestBody ApiOrder apiOrder) {
		return orderOperateService.queryOrderInfoOrList(apiOrder);
	}

	@ApiOperation(value = "客服查询订单信息")
	@RequestMapping(value = "test")
	public RestResult test() {
		orderLogisticsService.queryLogisticsInfo();
		return new RestResult();
	}
	@ApiOperation(value = "查询自提待收货订单列表")
	@RequestMapping(value = "queryPickAllList", method = RequestMethod.POST)
	public RestResult<List<FrontAllOrderInfo>> queryPickAllList(@RequestBody UserPageQuery request) {
		return orderQueryService.queryPickAllList(request);
	}
}
